using System;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// JSON工具类
/// </summary>
public static class JsonUtil
{
    /// <summary>
    /// 将对象序列化为JSON字符串
    /// </summary>
    /// <param name="obj">要序列化的对象</param>
    /// <returns>JSON字符串</returns>
    public static string ToJson(object obj)
    {
        try
        {
            return JsonUtility.ToJson(obj);
        }
        catch (Exception ex)
        {
            Debug.LogError($"序列化对象到JSON时出错: {ex.Message}");
            return "{}";
        }
    }

    /// <summary>
    /// 将JSON字符串反序列化为对象
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <param name="json">JSON字符串</param>
    /// <returns>反序列化的对象</returns>
    public static T FromJson<T>(string json) where T : new()
    {
        try
        {
            if (string.IsNullOrEmpty(json))
                return new T();

            return JsonUtility.FromJson<T>(json);
        }
        catch (Exception ex)
        {
            Debug.LogError($"从JSON反序列化对象时出错: {ex.Message}");
            return new T();
        }
    }

    /// <summary>
    /// 将JSON字符串反序列化为对象（带默认值）
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <param name="json">JSON字符串</param>
    /// <param name="defaultObj">默认对象</param>
    /// <returns>反序列化的对象</returns>
    public static T FromJson<T>(string json, T defaultObj)
    {
        try
        {
            if (string.IsNullOrEmpty(json))
                return defaultObj;

            return JsonUtility.FromJson<T>(json);
        }
        catch (Exception ex)
        {
            Debug.LogError($"从JSON反序列化对象时出错: {ex.Message}");
            return defaultObj;
        }
    }
}